<template>
    <div class="page-controller">
      <el-container>
        <el-container>
          <el-main>
            <FISearchForm
              class="box-radius2"
              ref="ruleFormRef"
              :id="`inqu_${tableId}`"
              v-model:form-value="state.query"
              :exclude-values="['postCname']"
              :table-column="columns"
              :wrapperSpan="searchWrapperSpan"
              @submit="searchFn"
              @reset="state.query.postCname = ''"
            >
              <el-col :span="searchWrapperSpan" class="flex-center">
                <FIFormItem prop="subjectId" label="授权主体编码">
                  <FIInput v-model="state.query.subjectId" clearable />
                </FIFormItem>
              </el-col>
              <el-col :span="searchWrapperSpan" class="flex-center">
                <FIFormItem name="subjectType" label="授权主体类别">
                  <!-- <FIInput v-model="state.query.subjectType" clearable /> -->
                  <FISelect v-model="state.query.subjectType" valueCustom="value" :options="dataArr" clearable />
                </FIFormItem>
              </el-col>
              <el-col :span="searchWrapperSpan" class="flex-center">
                <FIFormItem prop="objectId" label="授权资源编码">
                  <FIInput v-model="state.query.objectId" clearable />
                </FIFormItem>
              </el-col>
            </FISearchForm>
            <div class="margin-bottom20"></div>
            <FITable
              ref="tableRef"
              class="box-radius2"
              title="岗位列表"
              :id="`result_${tableId}`"
              :readonly="false"
              :data="state.dataList"
              primaryKey="groupId"
              v-model:columns="columns"
              :isLoading="isTableLoading"
              insertable
              deletable
              :showRowNo="true"
              :saveSuccessful="saveSuccessful"
              :pageConfig="pageConfig"
              @row-add-save="addRowSave"
              @table-refresh="searchFn"
              @selection-change="handleSelectionChange"
              @size-change="handleSizeChange"
              @current-page-change="handleCurrentChange"
              @action-click="actionClick"
              @row-delete="deleteRow"
            >
              
            </FITable>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
  import FICascaderTree from '@/components/FICascaderTree.vue'
  import FIAutoInput from '@/components/FIAutoInput.vue'
  import { apiRequestPost } from '@/api/globalApi.js'
  import LocalCache from '@/utils/cache'
  import { ElMessage } from 'element-plus'
  import { useMessage } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import {
    apiBaseDelete,
    apiBaseSave,
    apiBaseQuery,
    apiDeptMaintquery,
    apiPostquery,
  } from '@/api/user'
  import { getCurrentInstance } from 'vue'
  import {
  apiGetCodeitems,
} from '@/api/configEnvMaint/index.ts'
  const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
  const route = useRoute()
  
  const searchWrapperSpan = 8
  const showSearch = ref(true)
  const setShow = ref(false)
  const isTableLoading = ref(false)
  // 页面编码
  const tableId = 'usersManage'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const tableRef = ref(null)
  const editData = ref({})
  const orgList = ref([])
  const postList = ref([])
  const userlistCurrent = ref(1)
  const loadMoreEnd = ref(false)
  const dataArr = ref([])
  const state = reactive({
    query: {
      subjectId: '',
      subjectType: '',
      objectId: '',
      current: '1',
      size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const columns: Column[] = reactive([
    {
      label: '授权主体编码',
      prop: 'subjectId',
      align: 'center',
      queryName: '',
      editable: true,
      sortable: false,
      filterable: false,
      required: true,
      readonly: true,
      modelValue: { inputValue: '' },
      editType: 'input',
      // editConfig: {
      //    rules: { groupEname: [{ required: true, message: '请输入用户组编码', trigger: 'blur' }] },
      // },
    },
    {
      label: '授权主体类别',
      prop: 'subjectType',
      align: 'center',
      editable: true,
      required: true,
      editType: 'select',
      modelValue: [],
      editConfig: {
        rules: { subsecType: [{ required: true, message: '请选择', trigger: 'change' }] },
        options: [],
        selectBinds: {
          multiple: false,
          valueCustom: 'value',
        },
      },
    },
    {
      label: '授权资源编码',
      prop: 'objectId',
      align: 'center',
      editable: true,
      editType: 'input',
    },

    {
      label: '创建人',
      prop: 'recCreator',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '创建时间',
      prop: 'recCreateTime',
      align: 'center',
      editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '修改人',
      prop: 'recRevisor',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '修改时间',
      prop: 'recReviseTime',
      align: 'center',
      editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
  ])
  const checkedRows = ref([])
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    searchFn()
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn('page')
  }
  //操作
  const actionClick = (item, rowData, btnInfo) => {
    editData.value = rowData
    if (item.type == 'set') {
      setShow.value = true
    }
  }
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    isTableLoading.value = true
    state.query = obj.queryData
    columns.values = obj.columns
    if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    const par = {
      ...state.query,
    }
    // const apiUrl = proxy.$Button_api('query', route.name)
    apiBaseQuery(par)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else {
          // ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const handleSave = () => {
    
    isTableLoading.value = true
    saveSuccessful.value = false
    // const apiUrl = proxy.$Button_api('save', route.name)
    const arr = checkedRows.value.map((v) => {
      return {
        objectId: v.objectId,
        objectType: '1',//暂时随便写
        subjectId: v.subjectId,
        subjectType:v.subjectType
      }
    })
    apiBaseSave(arr)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          // saveSuccessful.value = true
          ElMessage.success(res.data.message)
          // tableRef.value.clearSelection()
          searchFn()
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
      })
  }
  const deleteRow = () => {
    if (!checkedRows.value.length) {
      useMessage().warning('请选择一条数据')
      return
    }
    // let ids = []
    // Array.isArray(checkedRows.value) &&
    //   checkedRows.value.forEach((item: any) => {
    //     if (item?.groupId) ids.push(item?.groupId)
    //   })
    console.log(checkedRows.value,'checkedRows.value')
    const arr = checkedRows.value.map((v) => {
      return {
        objectId: v.objectId,
        objectType: v.objectType,
        subjectId: v.subjectId,
        subjectType:v.subjectType
      }
    })
    isTableLoading.value = true
    // const apiUrl = proxy.$Button_api('delete', route.name)
    apiBaseDelete(arr)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          searchFn()
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
      })
  }
  const ruleFormRef = ref(null)
  
  const addRowSave = (data) => {
    handleSave()
  }
  const getOrgList = () => {
    let par = {
      current: 1,
      size: 999,
    }
    apiDeptMaintquery(par)
      .then((res) => {
        if (res.data.success) {
          // orgList.value = res.data.data.result
          for (let i of res.data.data.result) {
            const obj = {
              orgCname: i.orgCname,
              orgEname: i.orgEname,
              orgId: i.orgId,
            }
            orgList.value.push(obj)
          }
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const getPostList = (query) => {
    let par = {
      postAName: query || '',
      current: userlistCurrent.value,
      size: 10,
    }
    apiPostquery(par)
      .then((res) => {
        if (res.data.success) {
          for (let i of res.data.data.result) {
            const obj = {
              postCname: i.postCname,
              postEname: i.postEname,
              postId: i.postId,
            }
            postList.value.push(obj)
          }
          if (query) {
            postList.value = []
            postList.value = res.data.data.result
          }
          postList.value = postList.value.concat(res.data.data.result)
          if (userlistCurrent.value * 10 >= res.data.data.count) {
            loadMoreEnd.value = true
          }
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const smallCode = () => {
  apiGetCodeitems({ codesetCode: 'xs.auth.subjectType' })
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        dataArr.value = res.data.data.map((v) => {
          return {
            label: v.itemCname,
            value: v.itemCode,
          }
        })
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'subjectType') {
            v.editConfig.options = dataArr
          }
        })
      }
    })
    .catch((error: any) => {})
}
  onMounted(() => {
    smallCode()
    searchFn()
    getOrgList()
    getPostList('')
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
  })
  </script>
  <style lang="less" scoped></style>
  